package ad.manager.filecontentprovider;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        writeTxt();
        findViewById(R.id.btn_install).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uriForFile = getUriForFile(MainActivity.this, getFilesDir().getAbsolutePath() + "/a.txt");
                Log.d(TAG, "onClick: " + uriForFile);
                Intent intent = new Intent();
                intent.setPackage("ad.manager.testfileprovider");
                intent.setClassName("ad.manager.testfileprovider", "ad.manager.testfileprovider.MainActivity");
                intent.putExtra("uri", uriForFile.toString());

                //授权uri方法   grantUriPermission  授权后若应用正在运行立即生效否则下次应用启动生效  应用停止后授权会取消
                grantUriPermission("ad.manager.testfileprovider", uriForFile, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//授权uri

                //   intent.flags配合intent.data  也能实现uri授权
//                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//需要flag
//                intent.setData(uriForFile);// 授权uri  不授权uri无效
//                intent.setClipData(ClipData.newUri(getContentResolver(),"",uriForFile)); //授权uri  不授权uri无效
                startActivity(intent);

            }
        });
    }


    private void writeTxt() {
        String filePath = getFilesDir().getAbsolutePath() + "/a.txt";
        File file = new File(filePath);
        if (!file.exists()) {
            if (file.getParentFile() != null) {
                file.getParentFile().mkdirs();
            }
            try {
                writeText(filePath, "saasdaadad测试");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void writeText(String path, String content) throws IOException {
        File file = new File(path);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
        fileOutputStream.close();
    }


    /**
     * 安装APK
     *
     * @param context 上下文
     * @param apkPath APK路径
     */
    public static void installApk(Context context, String apkPath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(apkPath);
        String packageName = context.getPackageName();
        Log.d(TAG, "installApk: " + packageName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //这里要注意FileProvider一定要在AndroidManifest中去声明哦
            //同时com.mc.mcplatform代表你自己的包名

            Uri apkUri = FileProvider.getUriForFile(context, packageName + ".FileProvider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public static Uri getUriForFile(Context context, String apkPath) {


        File file = new File(apkPath);
        String packageName = context.getPackageName();
        Log.d(TAG, "installApk: " + packageName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //这里要注意FileProvider一定要在AndroidManifest中去声明哦
            //同时com.mc.mcplatform代表你自己的包名

            Uri apkUri = FileProvider.getUriForFile(context, packageName + ".FileProvider", file);
            return apkUri;
        } else {
            Uri uri = Uri.fromFile(file);
            return uri;
        }
    }
}